<?php

namespace App\Models;

use App\Jobs\SendMails;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Orders extends Model
{

    use SoftDeletes;

    protected $fillable = ['order_id', 'product_id', 'coupon_id', 'ord_class', 'product_price', 'ord_price', 'buy_amount', 'ord_title', 'search_pwd', 'account', 'ord_info', 'pay_ord', 'pay_way', 'buy_ip', 'ord_status'];//开启白名单字段


    /**
     * 关联商品表
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo(Products::class, 'product_id');
    }

    /**
     * 关联优惠码.
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function coupon()
    {
        return $this->belongsTo(Coupons::class, 'coupon_id');
    }

    /**
     * 关联支付方式
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function pay()
    {
        return $this->belongsTo(Pays::class, 'pay_way');
    }

    public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        static::saved(function ($model) {
            // 当代充商品状态，将会对顾客进行订单内容推送
            $order = [
                'created_at' => date('Y-m-d H:i'),
                'ord_title' => $model->ord_title,
                'webname' => config('webset.text_logo'),
                'weburl' => env('APP_URL'),
                'order_id' => $model->order_id,
                'ord_price' => $model->ord_price
            ];
            $to = $model->account;
            if ($model->ord_class == 2) {
                switch ($model->ord_status) {
                    case 1:
                        $mailtpl = Emailtpls::where('tpl_token', 'pending_order')->first()->toArray();
                        self::sendMailToOrderStatus($mailtpl, $order, $to);
                        break;
                    case 3:
                        $mailtpl = Emailtpls::where('tpl_token', 'completed_order')->first()->toArray();
                        self::sendMailToOrderStatus($mailtpl, $order, $to);
                        break;
                    case 4:
                        $mailtpl = Emailtpls::where('tpl_token', 'failed_order')->first()->toArray();
                        self::sendMailToOrderStatus($mailtpl, $order, $to);
                        break;
                }
            }
        });
    }

    /**
     * 根据不同状态提示不同邮件.
     * @param array $mailtpl
     * @param array $order
     * @param string $to
     */
    private static function sendMailToOrderStatus(array $mailtpl, array $order, string $to) :void
    {
        $mailtipsInfo = replace_mail_tpl($mailtpl, $order);
        SendMails::dispatch($to, $mailtipsInfo['tpl_content'], $mailtipsInfo['tpl_name']);
    }


}
